package com.zjj.bams.client;

import com.zjj.bams.entity.Account;
import com.zjj.bams.service.Bank;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.Socket;

/**
 * @author zhoujunjie
 * @desc TODO
 * @date
 */
public class ATMClient extends JFrame {

    //JPanel
    MainPanel mainPanel;
    LoginPanel loginPanel;
    RegisterPanel registerPanel;
    BusinessPanel businessPanel;

    //共同数据
    Bank bank;
    Account acc;

    //网络编程通信的资源
    Socket socket;
    PrintWriter pw;
    ObjectInputStream ois;

    //实例化
    public ATMClient() {
        //设置窗体的标题
        this.setTitle("ATM 取款机");
        //设置窗体的宽高
        this.setSize(480 , 650);
        //设置窗体的关闭方式  关闭即退出
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //设置窗体的居中显示
        this.setLocationRelativeTo(null);

        //初始化共同数据
        bank = Bank.getInstance();

        //启动客户端
        try {
            socket = new Socket("127.0.0.1" , 8899);
            pw = new PrintWriter(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());
        } catch (ConnectException e) {
            JOptionPane.showMessageDialog(this, "服务器未启动！");
            System.exit(0);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //关闭客户端 - 添加窗口关闭的事件
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                //发送关闭close客户端的指令
                pw.println("close");
                pw.flush();

                //空读处理
                try {
                    //空读
                    ois.readObject();
                    //关闭客户端的资源
                    socket.close();
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(ATMClient.this, "客户端已关闭！");
                } catch (ClassNotFoundException ex) {
                    throw new RuntimeException(ex);
                }
                System.exit(0);
            }
        });


        //实例化 JPanel
        mainPanel = new MainPanel(this);
        loginPanel = new LoginPanel(this);
        registerPanel = new RegisterPanel(this);
        businessPanel = new BusinessPanel(this);

        //将JPanel添加至JFrame窗体容器中，设置当前容器为卡片式布局
        Container container = this.getContentPane();
        container.setLayout(new CardLayout());
        //默认实现第一个JPanel
        container.add(mainPanel, "mainPanel");
        container.add(loginPanel, "loginPanel");
        container.add(registerPanel, "registerPanel");
        container.add(businessPanel, "businessPanel");
    }

    public static void main(String[] args) {
        new ATMClient().setVisible(true);
    }

}
